%遗传算法求解第二题
%%
%载入数据
clc;
clear;

load('SelectNode.mat');
load('MapData.mat');
load('PalletsData.mat');

global deltaS;
global S;
global S_bar;
global m_part12;
%可选参数
deltaS=50; %每个蓝点的取货误差限

%%
%计算各个绿点存货量s
[m_part11,n_part11]=size(PalletsData);
[m_part12,n_part12]=size(SelectNode);
PalletsTotal=zeros(m_part11,3); %该矩阵存储[X,Y,货量]
for i=1:1:m_part11
    PalletsTotal(i,1:2)=Pallets(i,1:2);
    for j=1:1:Pallets(i,4)
        PalletsTotal(i,3)=Pallets(i,2*j+4)+PalletsTotal(i,3);
    end   
end

TOtal=sum(PalletsTotal(:,3)); %计算总货量
S(:,1)=PalletsTotal(:,3);
S_bar=ceil(TOtal/m_part12);  %向上取整

%%
%建立绿点与蓝点间的距离矩阵L
%此处为节约时间，计算一次以后存储，后续直接读取

% l=zeros(m_part11,m_part12);
% for i=1:1:m_part11    
%     for j=1:1:m_part12
%         MobileOrder=GetTrajectory([PalletsTotal(i,1:2);SelectNode(j,2:3)]);
%         [m_part21,n_part21]=size(MobileOrder);
%         l(i,j)=m_part21-1;
%     end   
% end
% save('l.mat','l');

load('l.mat');
global l;

l_min=zeros(1,m_part11);
for i=1:1:m_part11
    l_min(1,i)=min(l(i,:));
end

% [c,ceq] = ellipsecons(l_min)
% [c,ceq] = ellipsecons(x)

%%
%遗传算法求解
% options = optimoptions('ga','ConstraintTolerance',1e-6,'PlotFcn', @gaplotbestf);
lb=zeros(1,m_part11);
ub=18*ones(1,m_part11);
fun=@fitnessfunction;
nvars=m_part11;
IntCon=1:1:nvars;
nonlcon=@ellipsecons;
% nonlcon=@ellipseconstest;
%  aaa=ones(1,148);

gaopts=gaoptimset('PopulationSize',100,'Generations',10000);  %遗传算法设置
gaopts=gaoptimset(gaopts,'InitialPopulation',l_min);    %设置初始种群
gaopts=gaoptimset(gaopts,'PlotFcns',{@gaplotbestf,@gaplotbestindiv});
gaopts=gaoptimset(gaopts,'StallGenLimit',Inf);
% A1=eye(148);
% A=[A1;-A1];
x = ga(fun,nvars,[],[],[],[],lb,ub,nonlcon,gaopts);

% x = ga(fun,nvars,[],[],[],[],lb,ub,[],gaopts);



%%
%绘图
% zeros



